package com.xuecheng.content.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.CoursePub;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
@RocketMQTransactionListener
@Slf4j
public class CoursePubTxMsgListener implements RocketMQLocalTransactionListener {
    @Autowired
    private CourseBaseService courseBaseService;
    @Autowired
    private CoursePubService coursePubService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            //1.获取业务数据,并解析
            Long courseBaseId = new Long(new String((byte[]) message.getPayload()));
            //2.调用Service层服务,执行本地事务
            this.courseBaseService.saveCoursePubAndModifyAuditStatus(courseBaseId);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (NumberFormatException e) {
            log.error("事务监听器执行本地事务失败:{}", e.getMessage());
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        Long courseBaseId = new Long(new String((byte[]) message.getPayload()));
        //1.判断课程审核状态
        CourseBase courseBase = this.courseBaseService.getById(courseBaseId);
        //判断课程审核状态
        String auditStatus = courseBase.getAuditStatus();
        if (!ObjectUtils.nullSafeEquals(auditStatus, CourseAuditEnum.AUDIT_PASTED_STATUS)) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //判断课程发布信息
        LambdaQueryWrapper<CoursePub> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CoursePub::getCourseId, courseBaseId);
        int count = this.coursePubService.count(queryWrapper);
        if (count < 1) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
